<template>
  <div>
      <el-row>
          <el-card shadow="hover" style="height: 70px;width: 100%">
              <el-form-item label="目标终端">
                  <el-cascader placeholder="设备ID"
                               :options="options"
                               :props="props"
                               filterable
                               :show-all-levels="false"
                               collapse-tags
                               @change="getDevice"
                  />
                  <el-button type="primary" class="container-header" style="position: relative; left: 20px">搜索</el-button>
              </el-form-item>
          </el-card>
      </el-row>
      <el-row>
          <el-col :span="13">
              <el-card class="box-card-left" :body-style="{padding: '0px'}">
                  <div ref="DTHTEMChart" style="width: 650px; height: 300px"></div>
              </el-card>
          </el-col>
          <el-col :span="13">
              <el-card class="box-card-left" :body-style="{padding: '0px'}">
                  <div ref="LIMCOLChart" style="width: 650px; height: 300px"></div>
              </el-card>
          </el-col>
          <el-col :span="13">
              <el-card class="box-card-left" :body-style="{padding: '0px'}">
                  <div ref="SMOKChart" style="width: 650px; height: 300px"></div>
              </el-card>
          </el-col>
          <el-col :span="13">
              <el-card class="box-card-main-left" :body-style="{padding: '0px'}">
                  <div ref="DEVICEChart" style="width:110%; height: 420px"></div>
              </el-card>
          </el-col>
          <el-col :span="13">
              <el-card class="box-card-main-right" :body-style="{padding: '0px'}">
                  <div ref="LIGHTChart" style="width:110%; height: 420px"></div>
              </el-card>
          </el-col>
      </el-row>
  </div>
</template>

<script setup lang="ts" name="datavisualization">
import {ref, onMounted} from 'vue'
// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts';
import API from "../utils/axios";
// 创建DOM引用
const DTHTEMChart = ref();
const LIMCOLChart = ref();
const SMOKChart = ref();
const DEVICEChart = ref();
const LIGHTChart = ref();
let myDTHTEMChart : echarts.EChartsOption
let mySMOKChart : echarts.EChartsOption
let myLIMCOLChart : echarts.EChartsOption
let myDEVICEChart : echarts.EChartsOption
let myLIGHTChart : echarts.EChartsOption
// 基于准备好的dom，初始化温湿度echarts实例
onMounted(() => {
    getRoomDeviceTree();
    getUsedCount();
    getOnlineDevice();
    myDTHTEMChart = echarts.init(DTHTEMChart.value,'dark');
    myLIMCOLChart = echarts.init(LIMCOLChart.value, 'dark');
    mySMOKChart = echarts.init(SMOKChart.value,'dark');
    myDEVICEChart = echarts.init(DEVICEChart.value,'dark');
    myLIGHTChart = echarts.init(LIGHTChart.value,'dark');
    // 灯光设备使用时长统计
    const option_LIGHT = {
        xAxis: {
            max: 'dataMax'
        },
        yAxis: {
            type: 'category',
            data: durationDeviceNameSet.value,
            inverse: true,
            animationDuration: 300,
            animationDurationUpdate: 300,
            max: 4 // only the largest 5 bars will be displayed
        },
        series: [
            {
                realtimeSort: true,
                name: '灯光设备累计使用时长（分/min）',
                type: 'bar',
                data: durationSet.value,
                label: {
                    show: true,
                    position: 'right',
                    valueAnimation: true
                }
            }
        ],
        legend: {
            show: true
        },
        animationDuration: 0,
        animationDurationUpdate: 5000,
        animationEasing: 'linear',
        animationEasingUpdate: 'linear'
    };

    // 设备在线数据集
    const option_DEVICE = {
        title: {
            text: '照明设备使用数量变化图',
            left: '36%'
        },
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            left: '5%',
            right: '15%',
            bottom: '10%'
        },
        xAxis: {
            data:['0min','5min','10min','15min','20min','25min','30min','35min','40min','45min','50min','55mim','60min']
        },
        yAxis: {
        },
        toolbox: {
            right: 10,
            feature: {
                dataZoom: {
                    yAxisIndex: 'none'
                },
                restore: {},
                saveAsImage: {}
            }
        },
        dataZoom: [
            {
                startValue: '0min'
            },
            {
                type: 'inside'
            }
        ],
        visualMap: {
            top: 50,
            right: 100,
            pieces: [
                {
                    gt: 0,
                    lte: 2,
                    color: '#93CE07'
                },
                {
                    gt: 2,
                    lte: 4,
                    color: '#FBDB0F'
                },
                {
                    gt: 4,
                    lte: 6,
                    color: '#FC7D02'
                },
                {
                    gt: 6,
                    lte: 8,
                    color: '#FD0100'
                },
                {
                    gt: 8,
                    color: '#AC3B2A'
                }
            ],
            outOfRange: {
                color: '#999'
            }
        },
        series: {
            name: '照明设备已开启数量:',
            type: 'line',
            data: [0,2,3,5,7,6,8,5,7,10,8,5,6],
            markLine: {
                silent: true,
                lineStyle: {
                    color: '#333'
                },
                data: [
                    {
                        yAxis: 2
                    },
                    {
                        yAxis: 4
                    },
                    {
                        yAxis: 6
                    },
                    {
                        yAxis: 8
                    },

                ]
            }
        }
    }

    // 温湿度数据集
    const option_DTHTEM = {
        title:{
            text: '温湿度实时数据',
            bottom: 20,
            right: 260
        },
        tooltip: {
            trigger: 'axis',
            // axisPointer: { type: 'cross' }
        },
        legend: {
        },
        xAxis: [
            {
                type: 'category',
                axisTick: {
                    alignWithLabel: true
                },
                data: [
                    '5min',
                    '10min',
                    '15min',
                    '20min',
                    '25min',
                    '30min',
                    '35min',
                    '40min',
                    '45min',
                    '50min',
                    '55min',
                    '60min'
                ]
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '湿度',
                min: 0,
                max: 100,
                position: 'right',
                axisLabel: {
                    formatter: '{value} %'
                }
            },
            {
                type: 'value',
                name: '温度',
                min: 0,
                max: 50,
                position: 'left',
                axisLabel: {
                    formatter: '{value} °C'
                }
            }
        ],
        series: [
            {
                name: '湿度',
                type: 'line',
                smooth: true,
                yAxisIndex: 0,
                data: [28, 32, 35, 27, 34, 29, 25, 30, 27, 34, 30, 26]
            },
            {
                name: '温度',
                type: 'line',
                smooth: true,
                yAxisIndex: 1,
                data: [52, 54, 49, 51, 45, 42, 53, 57, 54, 56, 48, 54]
            }
        ]
    };

    // 照明数据集
    const option_LIMCOL = {
        title:{
            text: '照明实时数据',
            bottom: 20,
            right: 270
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' }
        },
        legend: {
        },
        xAxis: [
            {
                type: 'category',
                axisTick: {
                    alignWithLabel: true
                },
                data: [
                    '5min',
                    '10min',
                    '15min',
                    '20min',
                    '25min',
                    '30min',
                    '35min',
                    '40min',
                    '45min',
                    '50min',
                    '55min',
                    '60min'
                ]
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '色温',
                min: 0,
                max: 10000,
                position: 'right',
                axisLabel: {
                    formatter: '{value} K'
                }
            },
            {
                type: 'value',
                name: '照度',
                min: 0,
                max: 1500,
                position: 'left',
                axisLabel: {
                    formatter: '{value} lx'
                }
            }
        ],
        series: [
            {
                name: '色温',
                type: 'line',
                smooth: true,
                yAxisIndex: 0,
                data: [3500, 3600, 3785, 4523, 5146, 4963, 4801, 4421, 4156, 3963, 3561, 3152]
            },
            {
                name: '照度',
                type: 'line',
                smooth: true,
                yAxisIndex: 1,
                data: [105, 165, 274, 291, 463, 601, 535, 661, 524, 495, 460, 397]
            }
        ]
    };

    // 烟雾浓度数据
    const option_SMOK = {
        visualMap: [
            {
                show: false,
                type: 'continuous',
                seriesIndex: 0,
                min: 1,
                max: 100
            }],
        title:{
            text: '烟雾浓度实时数据',
            bottom: 20,
            right: 250,
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' }
        },
        legend: {
        },
        xAxis: [
            {
                type: 'category',
                axisTick: {
                    alignWithLabel: true
                },
                data: [
                    '5min',
                    '10min',
                    '15min',
                    '20min',
                    '25min',
                    '30min',
                    '35min',
                    '40min',
                    '45min',
                    '50min',
                    '55min',
                    '60min'
                ]
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '烟雾浓度',
                min: 0,
                max: 10,
                axisLabel: {
                    formatter: '{value} %'
                }
            },
        ],
        series: [
            {
                name: '烟雾浓度',
                type: 'line',
                smooth: true,
                data: [1.2, 1.9, 0.7, 0.4, 0.8, 1.6, 1.9, 2.8, 4.3, 2.7, 3.1, 1.4]
            },
        ]
    };
// 绘制图表
    myDTHTEMChart.setOption(option_DTHTEM);
    myLIMCOLChart.setOption(option_LIMCOL);
    mySMOKChart.setOption(option_SMOK);
    myDEVICEChart.setOption(option_DEVICE);
    myLIGHTChart.setOption(option_LIGHT);
})
// 更新SMOKE视图
const updateViewSmokeChart = () => {
    const option_SMOK = {
        xAxis: [
            {
                data: timeSet.value
            }
        ],
        series:[
            {
                data:smokeScopeSet.value
            }
        ]
    }
    mySMOKChart.setOption(option_SMOK);
}
// 更新DTHTEM试图
const updateViewDTHTEMChart = () => {
    const option_DTHTEM = {
        xAxis: [
            {
                data: timeSet.value
            }
        ],
        series:[
            {
                yAxisIndex: 0,
                data: humiditySet.value
            },
            {
                yAxisIndex: 1,
                data: temperatureSet.value
            }
        ]
    }
    myDTHTEMChart.setOption(option_DTHTEM);
}
// 更新LIMCOL视图
const updateViewLIMCOLChart = () => {
    const option_LIMCOL = {
        xAxis: [
            {
                data: timeSet.value
            }
        ],
        series: [
            {
                yAxisIndex: 0,
                data: colorTemperatureSet.value
            },
            {
                yAxisIndex: 1,
                data: luminanceSet.value
            }
        ]
    }
    myLIMCOLChart.setOption(option_LIMCOL);
}
// 更新DEVICE试图
const updateViewDEVICEChart = () => {
    const option_DEVICE = {
        xAxis: [
            {
                data: onLineCountTimeSet.value
            }
        ],
        series:[
            {
                data:onLineCountSet.value
            }
        ]
    }
    myDEVICEChart.setOption(option_DEVICE);
}
// 更新myLIGHTChart视图
const updateViewLIGHTChart = () => {
    const option_LIGHT = {
        yAxis: [
            {
                data: durationDeviceNameSet.value
            }
        ],
        series:[
            {
                data:durationSet.value
            }
        ]
    }
    myLIGHTChart.setOption(option_LIGHT);
}

// 选择设备
const props = {
    multiple: false,
}
// 获取教室绑定设备信息
const options = ref([])
const getRoomDeviceTree = () => {
    API.post("/DeviceController/getDeviceTree")
        .then((res) => {
            options.value = res.data.data.map((item : any) => {
                return {value : item.roomNumber, label : item.roomName,
                    children : item.deviceChild.map((child : any) => {
                        return {value : child.deviceNumber, label : child.deviceName}
                    })}
            })
        })
}
// 获取当前操作设备,并发送请求改设备环境数据
let deviceValue = ref<string>();
const getDevice = (value : any) => {
    deviceValue.value = value[1];
    // 时间数据
    timeSet.value = []
// 环境光亮度数据
    luminanceSet.value = [];
// 环境光色温数据
    colorTemperatureSet.value = [];
// 温度数据
    temperatureSet.value = [];
// 湿度数据
    humiditySet.value = [];
// 烟雾浓度数据
    smokeScopeSet.value = [];
    updateViewLIGHTChart();
    updateViewDEVICEChart();
    updateViewLIMCOLChart();
    updateViewSmokeChart();
    updateViewDTHTEMChart();
}

// 初始化设备使用时长
const getUsedCount = () => {
  API.post("/DeviceController/getUsedCount")
      .then((res) => {
          console.log(res.data.data);
      })
      .catch((err) => {return err})
}

// 初始化已开启灯光设备数量数据
const getOnlineDevice = () => {
    API.post("/DeviceController/getOnlineDevice")
        .then((res) => {
            console.log(res.data.data);
        })
        .catch((err) => {return err})
}

let timeData = ref([])
// 建立WebSocket连接
const ws = new WebSocket("ws://localhost:8085/webSocket");
ws.onopen = function (event){
    console.log('建立连接');
}
ws.onclose = function (event){
    console.log('连接关闭');
}
ws.onmessage= function (event){
    // 进行弹窗提醒或其他操作
    try {
        // 将接收到的 JSON 字符串转换成 JavaScript 对象
        const message = JSON.parse(event.data);
        // 设备数据处理
        if (message.dataType == deviceValue.value){
            getEnvironmentData(message);
        }else if (message.dataType == "在线设备"){
            getOnlineDeviceCount(message);
        }else if (message.dataType == "在线时长"){
            getDuration(message);
        }
    } catch (error) {
        console.error('JSON 解析出错', error);
    }
}
ws.onerror= function (){
    alert('websocket通信发生错误！')
};

// 时间数据
let timeSet = ref([]);
// 环境光亮度数据
let luminanceSet = ref([]);
// 环境光色温数据
let colorTemperatureSet = ref([]);
// 温度数据
let temperatureSet = ref([]);
// 湿度数据
let humiditySet = ref([]);
// 烟雾浓度数据
let smokeScopeSet = ref([]);
const getEnvironmentData = (message : any) => {
    // 获取更新数据
    const socketData = message.dataBody;
    const time = socketData[0].environmentTime.substring(11)
    const data = {
        Luminance : socketData[0].environmentLuminance, ColorTemperature : socketData[0].environmentColortemperature, Temperature : socketData[0].environmentTemperature,
            Humidity : socketData[0].environmentHumidity, SmokeScope : socketData[0].environmentSmokescope, Time : time}
    // 时间
    if (timeSet.value.length === 12){
        timeSet.value.shift();
        timeSet.value.push(data.Time);
    }else {
        timeSet.value.push(data.Time);
    }
    // 环境光亮度
    if (luminanceSet.value.length === 12){
        luminanceSet.value.shift();
        luminanceSet.value.push(data.Luminance);
    }else {
        luminanceSet.value.push(data.Luminance);
    }
    // 环境光色温
    if (colorTemperatureSet.value.length === 12){
        colorTemperatureSet.value.shift();
        colorTemperatureSet.value.push(data.ColorTemperature);
    }else {
        colorTemperatureSet.value.push(data.ColorTemperature);
    }
    // 温度
    if (temperatureSet.value.length === 12){
        temperatureSet.value.shift();
        temperatureSet.value.push(data.Temperature);
    }else {
        temperatureSet.value.push(data.Temperature);
    }
    // 湿度
    if (humiditySet.value.length === 12){
        humiditySet.value.shift();
        humiditySet.value.push(data.Humidity);
    }else {
        humiditySet.value.push(data.Humidity);
    }
    console.log(humiditySet);
    // 烟雾浓度
    if (smokeScopeSet.value.length === 12){
        smokeScopeSet.value.shift();
        smokeScopeSet.value.push(data.SmokeScope);
    }else {
        smokeScopeSet.value.push(data.SmokeScope);
    }
    // 更新视图
    updateViewSmokeChart();
    updateViewDTHTEMChart();
    updateViewLIMCOLChart();
}
// 获取在线设备数量
const onLineCountSet = ref([]);
const onLineCountTimeSet = ref([])
const getOnlineDeviceCount = (message : any) => {
    const socketData = message.dataBody;
    const time = socketData[0].deviceOnlineTime.substring(11);
    const data = {onLineDeviceCount : socketData[0].onLineDeviceCount}
    // 在线设备数量时间轴
    if (onLineCountTimeSet.value.length === 12){
        onLineCountTimeSet.value.shift();
        onLineCountTimeSet.value.push(time);
    }else {
        onLineCountTimeSet.value.push(time);
    }
    // 在线设备数量数据集
    if (onLineCountSet.value.length === 12){
        onLineCountSet.value.shift();
        onLineCountSet.value.push(data.onLineDeviceCount);
    }else {
        onLineCountSet.value.push(data.onLineDeviceCount);
    }
    // 更新视图
    updateViewDEVICEChart();
}

// 获取设备在线统计时长
const durationDeviceNameSet = ref([]);
const durationSet = ref([]);
const getDuration = (message : any) => {
    const socketData = message.dataBody;
    const nameData = socketData.map((item : any) => {
        return item.deviceName;
    })
    const durationData = socketData.map((item : any) => {
        return item.deviceOnline;
    })
    durationDeviceNameSet.value = nameData;
    durationSet.value = durationData;
    // 更新视图
    updateViewLIGHTChart();
}
</script>

<style scoped>
.box-card-left {
    width: 650px;
    height: 279px;
    margin-top: 10px;
}
.box-card-main-left{
    width: 64%;
    position: absolute;
    top: 10px;
    left: 670px;
}
.box-card-main-right{
    width: 64%;
    position: absolute;
    top: 450px;
    left: 670px;
}
</style>
